package com.newenergy.light.Helper;

import android.content.Context;
import android.content.SharedPreferences;

import java.util.Set;

/**
 * 存储一些轻量级的缓存数据
 * <p/>
 * Created by grant on 2016/4/13.
 */
public class SPUtil {

    private  final static String SP_FILE_NAME="ball_light";
    private static SharedPreferences sharedPreferences;

    public static void init(Context context) {
        sharedPreferences = context.getSharedPreferences(
               SP_FILE_NAME, Context.MODE_PRIVATE);
    }

    public static void put(String key, Object value) {
        SharedPreferences.Editor edit = sharedPreferences.edit();
        if (value instanceof String) {
            edit.putString(key, (String) value);
        }
        if (value instanceof Integer) {
            edit.putInt(key, (Integer) value);
        }
        if (value instanceof Float) {
            edit.putFloat(key, (Float) value);
        }
        if (value instanceof Long) {
            edit.putLong(key, (Long) value);
        }
        if (value instanceof Boolean) {
            edit.putBoolean(key, (Boolean) value);
        }
        if (value instanceof Set) {
            edit.putStringSet(key, (Set<String>) value);
        }
        edit.apply();
    }

    public static int getInteger(String key, int defaultValue) {
        return sharedPreferences.getInt(key, defaultValue);
    }

    public static String getString(String key, String defaultValue) {
        return sharedPreferences.getString(key, defaultValue);
    }

    public static String[] getStringArray(String key) {
        String regularEx = "-";
        String[] str = null;
        SharedPreferences sp =sharedPreferences;
        String values;
        values = sp.getString(key, "");
        str = values.split(regularEx);

        return str;
    }

    public static void putStringArray(String key, String[] values) {
        String regularEx = "-";
        String str = "";
        SharedPreferences sp = sharedPreferences;
        if (values != null && values.length > 0) {
            for (String value : values) {
                str += value;
                str += regularEx;
            }
            SharedPreferences.Editor et = sp.edit();
            et.putString(key, str);
            et.commit();
        }
    }
}